<template>
  <div class="main">
    <div v-for="item in data.list" :key="item.id">
      <div v-if="item.userId==data.userId">
        <div class="master_username">
          昵称:&nbsp;
          {{ item.username }}
        </div>
        <div class="master_content" v-html="item.content"></div>
      </div>
      <div v-else>
        <div class="slave_username">
          昵称:&nbsp;
          {{ item.username }}
        </div>
        <div class="slave_content" v-html="item.content"></div>
      </div>
    </div>
    <MyEditor @sendContent="receiveChildContent"/>
  </div>
</template>

<script setup lang="ts">
// @ts-ignore
import cookie from 'js-cookie'
import {onMounted, reactive, ref, watch} from "vue";
import axios from "axios";
import MyEditor from '../components/MyEditor.vue'

interface Chat {
  userId: number,
  username: string,
  content: string
}

//聊天所需的参数
const chat = reactive<Chat>({
  userId: 0,
  username: '',
  content: ''
})

const data = reactive({
  list: [],//所有聊天记录
  userId: ''//用户id
})

//接收子组件传过来的值并新增聊天记录
const receiveChildContent = (e: string) => {
  chat.content = e
  //从cookie中获取用户id和用户名
  chat.userId = JSON.parse(cookie.get("user")).id
  chat.username = JSON.parse(cookie.get("user")).username
  axios.post("http://localhost:5001/chat/add", chat).then((res) => {
    handleList()
  })
}

//获取所有聊天记录
const handleList = () => {
  axios.get("http://localhost:5001/chat/getList").then((res) => {
    data.list = res.data
  })
}

onMounted(() => {
  //从cookie中获取用户id
  data.userId = JSON.parse(cookie.get("user")).id
  setInterval(()=>{
    handleList()
  },100)
})
</script>

<style lang="less" scoped>
.main {
  width: 500px;
  height: 100%;
  border: 1px solid black;

  .master_username {
    color: red;
    margin: 10px;
  }

  .master_content {
    margin-left: 10px;
    margin-top: 5px;
  }

  .slave_username {
    color: black;
    margin: 10px 10px 10px 400px;
  }

  .slave_content {
    margin-left: 420px;
    margin-top: 5px;
  }
}
</style>